#include "qmythread.h"
#include <QSemaphore>

const int BufferSize = 8;
int buffer1[BufferSize];
int buffer2[BufferSize];

int currentBuff = 1; //当前正在写入的Buffer
int buffNO = 0;      //采集的缓冲区序号

quint8 counter = 0;   //数据生成器

QSemaphore emptyBuffs(2); //信号量，空的缓冲区个数，初始资源个数为2
QSemaphore fullBuffs;     //满的缓冲区个数，初始资源为0

void QThreadDAQ::run(){
    buffNO = 0;
    currentBuff = 1;
    counter = 0;
    int n = emptyBuffs.available();
    if(n < 2){                     //保证线程启动时emptyBuffers.avaliable == 2
        emptyBuffs.release(2 - n);
    }
    while(!m_stop){
        emptyBuffs.acquire();      //获取一个空的缓冲区
        //产生一个缓冲区的数据
        for (int i = 0; i < BufferSize; i++){
            //向缓冲区写入数据
            if (currentBuff == 1){
                buffer1[i] = counter;
            }else {
                buffer2[i] = counter;
            }
            counter++; //模拟数据采集卡产生数据
            msleep(50);
        }
        buffNO++; //缓冲区信号
        if(currentBuff == 1){
            currentBuff = 2;
        }else {
            currentBuff = 1;
        }
        fullBuffs.release();//释放一个缓冲区
    }
}

void QThreadShow::run(){
    m_stop = false;
    int n = fullBuffs.available();
    if (n > 0){
        fullBuffs.acquire(n);   //将fullBuffs的可用资源数初始化为0
    }
    while(!m_stop){
        fullBuffs.acquire();//等待有缓冲区满， 当fullBuffs.avaliable==0阻塞
        int buffeData[BufferSize];
        int seq = buffNO;

        if (currentBuff == 1){  //如果当前在写入的缓冲区是1， 那么满的缓冲区是2
            //拷贝缓冲区数据
            for (int i = 0 ; i < BufferSize; i++){
                buffeData[i] = buffer2[i];
            }
        }else {
            for (int i = 0 ; i < BufferSize; i++){
                buffeData[i] = buffer1[i];
            }
        }
        emptyBuffs.release();//释放一个空的缓冲区
        emit newValue(buffeData, BufferSize, seq);//给主线程传递数据
    }
}

QThreadDAQ::QThreadDAQ(){

}

QThreadShow::QThreadShow(){

}
